// 导入 mongoose 模块
const mongo = require("mongoose");

// 连接 mongodb 数据库
mongo.connect("mongodb://127.0.0.1:27017/bilibili");

// 设置回调
mongo.connection.once("open", () => {
  // 创建文档结构
  let novelSchema = new mongo.Schema({
    name: String,
    author: String,
    price: Number,
    is_hot: Boolean,
  });

  // 创建文档结构对象
  let novelModel = mongo.model("novel", novelSchema);

  // 更新文档
  /* novelModel.updateOne(
    {
      name: "黑暗王者",
    },
    {
      price: 99.9,
    },
    (err, data) => {
      if (err) {
        console.log(err);
        return;
      }
      console.log(data);
    },
  ); */

  // 批量更新
  novelModel.updateMany(
    {
      author: "甲鱼不是龟",
    },
    {
      is_hot: true,
    },
    (err, data) => {
      if (err) {
        console.log(err);
        return;
      }
      console.log(data);
    },
  );

  console.log("连接成功");
});

// 连接失败
mongo.connection.on("error", () => {
  console.log("连接失败");
});

// 连接关闭
mongo.connection.on("close", () => {
  console.log("连接关闭");
});
